package com.minio.controller;

import cn.hutool.core.util.ZipUtil;
import io.minio.*;
import io.minio.errors.*;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @Description
 * @Author 顾志杰
 * @Date 2022/4/13 10:11
 */
@RestController
@RequestMapping("/minio")
public class MinioTestController {

  @Resource
  private MinioClient minioClient;


  @PostMapping("upload")
  public String upload(MultipartFile file) throws FileNotFoundException {
    try{
      PutObjectArgs objectArgs = PutObjectArgs.builder().object(file.getOriginalFilename())
        .bucket("test") //桶名称
        .contentType(file.getContentType())
        .stream(file.getInputStream(),file.getSize(),-1).build();

      ObjectWriteResponse objectWriteResponse = minioClient.putObject(objectArgs);
      return "ok";
    } catch (Exception e) {
      e.printStackTrace();
      return e.getMessage();
    }
  }


  @GetMapping("/downloadMultiFileToMinIO")
  public void downloadMultiFileToMinIO(HttpServletResponse response) throws IOException, ServerException, InsufficientDataException, ErrorResponseException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
    List<String> fileUrlList = new ArrayList<>(Arrays.asList("WechatIMG6596.jpeg","顾志杰-Java.pdf","/test/名你自己改吧.xlsx"));
    //被压缩文件InputStream
    InputStream[] srcFiles = new InputStream[fileUrlList.size()];
    //被压缩文件名称
    String[] srcFileNames = new String[fileUrlList.size()];
    for (int i = 0; i < fileUrlList.size(); i++) {
      String fileUrl = fileUrlList.get(i);
      GetObjectArgs objectArgs = GetObjectArgs.builder().bucket("test")
        .object(fileUrl).build();
      InputStream inputStream = minioClient.getObject(objectArgs);
      if (inputStream == null) {
        continue;
      }
      srcFiles[i] = inputStream;
      String[] splitFileUrl = fileUrl.split("/");
      srcFileNames[i] = splitFileUrl[splitFileUrl.length - 1];
    }
    response.setCharacterEncoding("UTF-8");
    response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("下载测试.zip", "UTF-8"));
    //多个文件压缩成压缩包返回
    ZipUtil.zip(response.getOutputStream(), srcFileNames, srcFiles);
  }


  /**
   * 下载文件
   * @param filename
   */
  @GetMapping("/download/{filename}")
  public void download(@PathVariable String filename, HttpServletResponse res){

    GetObjectArgs objectArgs = GetObjectArgs.builder().bucket("test")
      .object(filename).build();

    try (GetObjectResponse response = minioClient.getObject(objectArgs)){
      byte[] buf = new byte[1024];

      int len;

      try (FastByteArrayOutputStream os = new FastByteArrayOutputStream()){

        while ((len=response.read(buf))!=-1){

          os.write(buf,0,len);

        }
        os.flush();

        byte[] bytes = os.toByteArray();

        res.setCharacterEncoding("utf-8");
        res.setContentType("application/force-download");// 设置强制下载不打开
        res.addHeader("Content-Disposition", "attachment;fileName=" + filename);
        try ( ServletOutputStream stream = res.getOutputStream()){
          stream.write(bytes);
          stream.flush();
        }
      }

    } catch (Exception e) {
      e.printStackTrace();
    }
  }




}
